const Sequelize = require("sequelize")
const { Op } = require("sequelize")

const {
  Goods,
  GoodsAttr,
  GoodsAttrValue,
  GoodsAttrResult,
  GoodsAttrConfig,
  GoodsStock,
  Store,
  StoreHouse,
  OrderGoods
} = require("../model")
const utils = require("../utils/index.js")
const _ = require("lodash")

// const { sqlConn } = require("../db/connect")

// const GoodsHasOneAttrConfig = (asName) => { return Goods.hasOne(GoodsAttrConfig, { foreignKey: 'goods_id', as: asName }); }
const GoodsHasOneAttrConfig = Goods.hasOne(GoodsAttrConfig, {
  foreignKey: "goods_id",
  constraints: false,
  as: "attrConfig"
})
const GoodsHasManyAttr = Goods.hasMany(GoodsAttr, {
  foreignKey: "goods_id",
  constraints: false,
  as: "attrData"
})
const GoodsHasManyAttrValue = Goods.hasMany(GoodsAttrValue, {
  // targetKey: 'id',
  foreignKey: "goods_id",
  constraints: false,
  as: "attrValue",
  order: ["sort", "ASC"]
})

const GoodsHasManyStock = GoodsAttrValue.hasMany(GoodsStock, {
  // foreignKey: "goods_id",
  foreignKey: "sku_id",
  constraints: false,
  as: "attrStock",
  // order: ["sort", "ASC"]
})

const GoodsHasOneAttrResult = Goods.hasOne(GoodsAttrResult, {
  foreignKey: "goods_id",
  constraints: false,
  as: "attrResult"
})

const createGoods = async params => { // 添加商品
  const {
    goods_name,
    full_goods_name,
    cat_id,
    attr = "",
    stock = "0",
    sales = "0",
    unit_name,
    unit_name2 = "",
    unit_convert = 1,
    unit_convert2 = 1,
    weight = 0,
    desc = "",
    sort = 500,
    store_id,
    is_hot = 0,
    is_recommend = 0,
    status = 1,
    is_delete = 0,
    slider_image = "",
    content,
    attr_list = [],
    goods_type = 1
  } = params
  let isFlag = false
  let goods = null
  let configData = {}

  try {
    goods = await Goods.findOrCreate({
      where: { store_id, goods_name, full_goods_name },
      defaults: {
        goods_name,
        full_goods_name,
        cat_id,
        attr,
        stock,
        sales,
        unit_name,
        unit_name2,
        unit_convert,
        unit_convert2,
        weight,
        desc,
        sort,
        store_id,
        is_hot,
        is_recommend,
        status,
        is_delete,
        slider_image,
        content
      }
    })
    isFlag = utils.handleCreateIsSuccess(goods);  // 是否新增成功
    console.log(
      "createGoods--goods:%s--isFlag: %s==",
      JSON.stringify(goods),
      isFlag
    )
    if (isFlag) {
      if (attr_list.length === 0) { // 单规格
        const defaultAttr = {
          goods_id: goods[0].id,
          sku: "默认",
          store_id,
          store_house_id: "",
          stock: 0,
          cordon: goods[0].cordon,
          sales: 0,
          price: 0,
          cost_price: 0,
          image: "",
          weight: 0,
          volume: 0,
          sort: 500
        }
        configData = JSON.stringify([defaultAttr])
      } else {  // 多规格
        configData = JSON.stringify(attr_list)
      }
      console.log("createGoods--configData==%s==", configData)

      // const attrConfig = await GoodsAttrConfig.findOrCreate({
      //   where: { goods_id: goods[0].id },
      //   defaults: { goods_id: goods[0].id, config: configData }
      // })
      bulkCreateGoodsAttr(params, goods[0].id, store_id)
      // console.log("createGoods--attrConfig==%s==", JSON.stringify(attrConfig))
    }
  } catch (e) {
    console.log("createGoods--e==%s", e)
    return null
  }
  return goods
}
// 新增商品直接 向 GoodsAttrValue 插入数据（2022.4.9 废弃）
const createGoods2 = async params => {
  const {
    goods_name,
    full_goods_name,
    cat_id,
    attr = "",
    stock = "0",
    sales = "0",
    unit_name,
    unit_name2 = "",
    unit_convert = 1,
    unit_convert2 = 1,
    weight = 0,
    desc = "",
    sort = 500,
    store_id,
    is_hot = 0,
    is_recommend = 0,
    status = 1,
    is_delete = 0,
    slider_image = "",
    content,
    attr_list = []
  } = params
  let isFlag = false
  let goods = null
  let storeHouseList = []
  let attrList = []
  console.log("createGoods--attr_list:%s==", JSON.stringify(attr_list))

  try {
    goods = await Goods.findOrCreate({
      where: { store_id, goods_name, full_goods_name },
      defaults: {
        goods_name,
        full_goods_name,
        cat_id,
        attr,
        stock,
        sales,
        unit_name,
        unit_name2,
        unit_convert,
        unit_convert2,
        weight,
        desc,
        sort,
        store_id,
        is_hot,
        is_recommend,
        status,
        is_delete,
        slider_image,
        content
      }
    })
    storeHouseList = await StoreHouse.findAll({
      where: { store_id, is_show: 1 }
    })
    console.log(
      "createGoods--storeHouseList:%s==",
      JSON.stringify(storeHouseList)
    )
    isFlag = utils.handleCreateIsSuccess(goods)
    console.log(
      "createGoods--goods:%s--isFlag: %s==",
      JSON.stringify(goods),
      isFlag
    )
    if (isFlag) {
      const defaultAttr = {
        goods_id: goods[0].id,
        sku: "默认",
        store_house_id: "",
        stock: 0,
        sales: 0,
        price: 0,
        cost_price: 0,
        image: "",
        weight: 0,
        volume: 0
      }
      if (storeHouseList.length > 0) {
        if (attr_list.length === 0) {
          attrList = storeHouseList.map(item => {
            const attrItem = JSON.parse(JSON.stringify(defaultAttr))
            attrItem.store_house_id = item.id
            return attrItem
          })
        } else {
          storeHouseList.forEach(storeHouseItem => {
            attr_list.forEach(attr => {
              const attrItem = {
                goods_id: goods[0].id,
                sku: attr.sku,
                store_house_id: storeHouseItem.id,
                stock: attr.stock || 0,
                sales: attr.sales || 0,
                price: attr.price || 0,
                cost_price: attr.cost_price || 0,
                image: attr.image || "",
                weight: attr.weight || 0,
                volume: attr.volume || 0
              }
              attrList.push(attrItem)
            })
          })
        }
      }
      console.log("createGoods--attrList==%s==", JSON.stringify(attrList))

      if (attrList.length > 0) {
        const attrResult = await GoodsAttrValue.bulkCreate(attrList, {
          updateOnDuplicate: [
            "stock",
            "sales",
            "price",
            "cost_price",
            "image",
            "weight",
            "volume"
          ]
        })
        console.log("createGoods--attrResult==%s==", JSON.stringify(attrResult))
      }
      // console.log('createGoods--storeHouseList:%s--attrList:%s==', JSON.stringify(storeHouseList), JSON.stringify(attrList), storeHouseList.length, attrList.length);

      // const goodsAttr = await GoodsAttr.findOrCreate({ where: { goods_id: attr.goods_id, attr_name: attr.attr_name }, defaults: { ...attr }});
      // console.log('goodsAttr==%s==', JSON.stringify(goodsAttr));
      // const resultData = {
      //   attrs: [attr.attr_name],
      //   values: [attr.attr_values]
      // }
      // const attrResult = {
      //   goods_id: goods[0].id,
      //   result: JSON.stringify(resultData)
      // }
      // const goodsAttrResult = await GoodsAttrResult.findOrCreate({ where: { goods_id: attrResult.goods_id  }, defaults: { ...attrResult }});
      // console.log('createGoods--attrResult==%s==', JSON.stringify(attrResult));
    }
  } catch (e) {
    console.log("createGoods--e==%s", e)
    return null
  }
  return goods
}

// GoodsAttrConfig 新增，修改
const handleAttrConfig = async params => { }

const updateGoods = async params => {
  const {
    id,
    goods_name,
    full_goods_name,
    cat_id,
    attr = "",
    stock = "0",
    sales = "0",
    unit_name,
    unit_name2 = "",
    unit_convert = 1,
    unit_convert2 = 1,
    weight = 0,
    desc = "",
    sort = 500,
    store_id,
    is_hot = 0,
    is_recommend = 0,
    status = 1,
    is_delete = 0,
    slider_image = "",
    content,
    attr_list = []
  } = params
  let isFlag = false
  let goods = null
  let storeHouseList = []
  let attrList = []
  console.log("updateGoods--attr_list:%s==", JSON.stringify(attr_list))
  const goodsParams = {
    goods_name,
    full_goods_name,
    cat_id,
    attr,
    stock,
    sales,
    unit_name,
    unit_name2,
    unit_convert,
    unit_convert2,
    weight,
    desc,
    sort,
    store_id,
    is_hot,
    is_recommend,
    status,
    is_delete,
    slider_image,
    content
  }
  console.log("updateGoods--goodsParams:%s==", JSON.stringify(goodsParams))
  try {
    goods = await Goods.update(goodsParams, { where: { id: params.id } });
    console.log('updateGoods--goods==', JSON.stringify(goods));
    return { code: 200, data: true,  msg: '更新成功' };
  } catch (e) {
    console.log("createGoods--e==%s", e)
    return { code: 500, data: false, msg: '更新失败' };
  }
}

// 新增、修改商品规格
const bulkCreateGoodsAttr = async (params, goods_id, store_id) => {
  console.log(
    "bulkCreateGoodsAttr--goods_id: %s--store_id: %s==",
    goods_id,
    store_id
  )
  try {
    const { attr_list } = params
    console.log(
      "bulkCreateGoodsAttr--attr_list: %s==",
      JSON.stringify(attr_list)
    )
    if (attr_list.length) {
      let attrList = []
      attr_list.forEach(attr => {
        const attrItem = {
          goods_id,
          goods_name: attr.goods_name,
          sku: attr.sku,
          // store_house_id: storeHouseList[0].id,
          store_house_id: "",
          stock: attr.stock || 0,
          sales: attr.sales || 0,
          price: attr.price || 0,
          cost_price: attr.cost_price || 0,
          image: attr.image || "",
          weight: attr.weight || 0,
          volume: attr.volume || 0
        }
        attrList.push(attrItem)
      })
      
      console.log(
        "bulkCreateGoodsAttr--attrList: %s==",
        JSON.stringify(attrList)
      )
      if (attrList.length > 0) {
        const attrResult = await GoodsAttrValue.bulkCreate(attrList, {
          updateOnDuplicate: [
            "goods_name",
            "stock",
            "sales",
            "price",
            "cost_price",
            "image",
            "weight",
            "volume",
            "sort"
          ]
        })

        console.log(
          "bulkCreateGoodsAttr--attrResult==%s==",
          JSON.stringify(attrResult)
        )
        return attrResult
      }
    }
  } catch (e) {
    console.log("bulkCreateGoodsAttr--e== %s==", e)
    return null
  }
}
const bulkCreateGoodsAttr2 = async (params, goods_id, store_id) => {
  console.log(
    "bulkCreateGoodsAttr--goods_id: %s--store_id: %s==",
    goods_id,
    store_id
  )
  try {
    const { attr_list } = params
    console.log(
      "bulkCreateGoodsAttr--attr_list: %s==",
      JSON.stringify(attr_list)
    )
    if (attr_list.length) {
      let attrList = []
      let newAttrList = [] // 新增规格
      attr_list.forEach(attr => {
        if (attr.store_house_id) {
          attrList.push(attr)
        }
        //  else {
        //   // store_house_id 不存在说明是新增的商品规格
        //   newAttrList.push(attr)
        // }
      })
      if (newAttrList.length) {
        // let storeHouseList = await StoreHouse.findAll({
        //   where: { store_id, is_show: 1 }
        // })
        // storeHouseList.forEach(storeHouseItem => {
          newAttrList.forEach(attr => {
            const attrItem = {
              goods_id,
              goods_name: attr.goods_name,
              sku: attr.sku,
              // store_house_id: storeHouseList[0].id,
              store_house_id: null,
              stock: attr.stock || 0,
              sales: attr.sales || 0,
              price: attr.price || 0,
              cost_price: attr.cost_price || 0,
              image: attr.image || "",
              weight: attr.weight || 0,
              volume: attr.volume || 0
            }
            attrList.push(attrItem)
          })
        // })
      }
      
      console.log(
        "bulkCreateGoodsAttr--attrList: %s==",
        JSON.stringify(attrList)
      )
      if (attrList.length > 0) {
        const attrResult = await GoodsAttrValue.bulkCreate(attrList, {
          updateOnDuplicate: [
            "goods_name",
            "stock",
            "sales",
            "price",
            "cost_price",
            "image",
            "weight",
            "volume",
            "sort"
          ]
        })

        console.log(
          "bulkCreateGoodsAttr--attrResult==%s==",
          JSON.stringify(attrResult)
        )
        return attrResult
      }
    }
  } catch (e) {
    console.log("bulkCreateGoodsAttr--e== %s==", e)
    return null
  }
}

// 商品规格
const editGoodsAttr = async params => {
  bulkCreate
}

/**
 * 更新商品库存 (2023.8.16 使用)
 * @param {*} order_id
 * isAllowLoad: 判断是否允许库存为负数
 * operation: add:加; reduce:减;  cover: 覆盖
 */
const updataStock = async (order_id) => {
  // console.log("updataStock--params: %s", JSON.stringify(params));
  if (!order_id) {
    return { code: 500, success: false, msg: '订单号不存在' } 
  }
  // try {
    // order_type 订单类型：1: 采购入库，2: 销售出库，3: 同价调拨， 4: 其他入库，5: 采购退货，6: 报溢单，7: 报损单，8: 其他出库
    // 查询订单商品数据
    const orderGoods = await OrderGoods.findAll({
      where: { order_id }
    });
    console.log("updataStock--orderGoods: %s", JSON.stringify(orderGoods));
    if (orderGoods.length) {
      let skuIds = [];  // 收集商品规格ID
      let orderGoodsList = [];  // 整合订单商品信息 (处理订单中存在多条相同商品数据，如赠送)
      
      orderGoods.forEach((d, i) => {
        let skuItem = JSON.parse(JSON.stringify(d));

        if (skuIds.includes(d.sku_id+'')) {
          const skuIndex = orderGoodsList.findIndex(s => s.sku_id === d.sku_id && s.store_house_id === d.store_house_id);
          console.log("updataStock--skuIndex: %s",  skuIndex);
          
          if (skuIndex > -1) {
            const skuOne = JSON.parse(JSON.stringify(orderGoodsList[skuIndex]));  // 获取已记录数据
            const goods_num = skuOne.goods_num + d.goods_num;
            skuItem = { ...skuOne, goods_num };
            orderGoodsList[skuIndex] = skuItem;
          }
          else {
            orderGoodsList.push(JSON.parse(JSON.stringify(skuItem)));
          }
        }
        else {
          skuIds.push(d.sku_id+'')
          orderGoodsList.push(JSON.parse(JSON.stringify(skuItem)));
        }
      })
      console.log("updataStock--skuIds: %s", JSON.stringify(skuIds));
      console.log("updataStock--orderGoodsList: %s", JSON.stringify(orderGoodsList));
      const stockRes = await GoodsStock.findAll({
        where: {
          sku_id: {
            [Sequelize.Op.in]: skuIds
          }
        }
      })
      console.log("updataStock--stockRes: %s", JSON.stringify(stockRes));

      const stockIds = stockRes.length ? stockRes.map(d => d.sku_id) : [];
      console.log("updataStock--stockIds: %s==", JSON.stringify(stockIds));

      let newStockList = [];
      orderGoodsList.forEach(d => {
        // const item = Object.assign({}, d);
        let item = JSON.parse(JSON.stringify(d));
        const orderType = handleOrderType(d.order_type);
        const goods_num = orderType ? orderType * d.goods_num : 0;
        console.log("updataStock--item: %s--%s==", d.sku_id, orderType);
        if (orderType) {
          if (stockIds.length && stockIds.includes(d.sku_id)) {  // 库存表存在, 更新数据
            // let stockItem = JSON.parse(JSON.stringify(stockRes.find(s => s.sku_id === d.sku_id && s.store_house_id === d.store_house_id)));
            const stockIndex = stockRes.findIndex(s => s.sku_id === d.sku_id && s.store_house_id === d.store_house_id);
            const newIndex = newStockList.findIndex(n => n.sku_id === d.sku_id && n.store_house_id === d.store_house_id)
            
            if (newIndex >= 0) {  //
              if (stockIndex >= 0) {  // 已记录 & 已存在
                newStockList[newIndex].stock += goods_num;
              }
              else {  // 已记录 & 不存在
                item.stock = goods_num;
                newStockList.push(item);
              }
            }
            else if (stockIndex >= 0) {
              let stockItem = stockRes[stockIndex];
              const stock = stockItem.stock + goods_num;
              stockItem.stock = stock
              newStockList.push(stockItem);
            }
            else {
              item.stock = goods_num;
              newStockList.push(item);
            }
            // const newIndex = newStockList.findIndex(n => n.sku_id === d.sku_id && n.store_house_id === d.store_house_id)
            // console.log("updataStock--newIndex: %s==", newIndex);
            
            // if (orderType) {
            //   if (newIndex >= 0) {
            //     const stock = stockItem.stock + goods_num;
            //     stockItem = JSON.parse(JSON.stringify(newStockList[newIndex]));
            //     newStockList[newIndex].stock = stockItem.stock + stock;
            //   }
            //   else {
            //     newStockList.push(item);
            //   }
            // }
            // if (orderType) {  // 1: 入库, -1: 出库, 0: 未知类型不做处理
            //   const stock = stockItem.stock + goods_num;
            //   item = {...stockItem, stock};
            //   if (orderType === 1) {
            //     item.price = d.goods_price
            //   }
            //   newStockList.push(item);
            // }
          }
          else {  // 库存表不存在, 插入数据
            item.stock = goods_num;
            newStockList.push(item);
          }
        }
      })
      console.log("updataStock--newStockList: %s==", JSON.stringify(newStockList));
      const list = JSON.parse(JSON.stringify(newStockList));
      const list2 = [{"update_time":"2023-08-17 20:48:37","sku_id":1,"store_house_id":3,"stock":5120,"price":"10","cost_price":null},{"update_time":"2023-08-17 22:28:40","sku_id":1,"store_house_id":1,"stock":1100,"price":null,"cost_price":null}]

      // const result = await GoodsStock.bulkCreate(list, { updateOnDuplicate: true });
      const result = await GoodsStock.bulkCreate(list, {
        updateOnDuplicate: [
          // "sku_id",
          // "store_house_id",
          "stock",
          "price",
          "cost_price"
        ]
      });
      // GoodsStock.bulkCreate(list, { 
      //   updateOnDuplicate: [
      //     // "sku_id",
      //     // "store_house_id",
      //     "stock",
      //     "price",
      //     "cost_price"
      //   ]
      //  }).then(result => {
      //   console.log("bulkCreate--res: %s", JSON.stringify(result));
      // }).catch(err => {
      //   console.log("bulkCreate--err: %s", err);
      // });

      console.log("updataStock--result: %s", JSON.stringify(result));
      return result;
    }
    else {
      return { code: 500, success: false, msg: '未找到订单商品' } 
    }
  // } catch (err) {
  //   console.log("updataStock--err: %s", JSON.stringify(err));
  //   return err
  // }
}
/**
 * 更新商品库存 (2023.8.16弃用)
 * @param {*} params
 * isAllowLoad: 判断是否允许库存为负数
 * operation: add:加; reduce:减;  cover: 覆盖
 */
const updataStock2 = async params => {
  console.log("updataStock--params: %s", JSON.stringify(params));
  const { goods_list, store_id, isAllowLoad, operation } = params
  let orderGoodsNum = {} // 统计同一商品规格数量
  const goodsParams = goods_list.map(d => {
    const goodsItem = {
      goods_id: d.goods_id,
      sku: d.goods_sku,
      store_house_id: d.store_house_id
    }
    if (orderGoodsNum[`${d.goods_id}_${d.goods_sku}_${d.store_house_id}`]) {
      orderGoodsNum[`${d.goods_id}_${d.goods_sku}_${d.store_house_id}`] += d.goods_num
    } else {
      orderGoodsNum[`${d.goods_id}_${d.goods_sku}_${d.store_house_id}`] = d.goods_num
    }
    return goodsItem
  })
  console.log("订单数量--orderGoodsNum: %s==", JSON.stringify(orderGoodsNum));
  let goodsStocks = await GoodsAttrValue.findAll({
    where: {
      [Op.or]: goodsParams
      // [Op.or]: [{ goods_id: 86, sku: '透明', store_house_id: 1 }]
    }
  })
  console.log("商品库存：updataStock--goodsStocks: %s==", JSON.stringify(goodsStocks))
  let goodsAttrList = []
  let msg = ""
  for (let index = 0; index < goods_list.length; index++) { // 遍历订单中的商品
    const goodsListItem = goods_list[index];
    console.log('goodsListItem--index:%s--%s==', index, JSON.stringify(goodsListItem));
    // goods_list.forEach(async (goodsListItem, index) => { 
    const goodsItemIndex = goodsStocks.findIndex(g => {  // 获取商品库存信息
      return (
        g.goods_id === goodsListItem.goods_id &&
        g.sku === goodsListItem.goods_sku &&
        g.store_house_id === goodsListItem.store_house_id
      )
    })
    const goodsItemStock = goodsItemIndex >= 0 ? goodsStocks[goodsItemIndex] : GoodsAttrValue.defaultValue();
    console.log("商品库存信息--goodsItemIndex: %s--goodsItemStock==:-%s---", goodsItemIndex, JSON.stringify(goodsItemStock));
    if (goodsItemStock?.id) { // 商品库存信息存在
      console.log("000---order.stock: %s--goods.stock: %s==", orderGoodsNum[`${goodsListItem.goods_id}_${goodsListItem.goods_sku}_${goodsListItem.store_house_id}`], goodsItemStock.stock);
      if (operation === "add") {
        // 库存加
        goodsItemStock.stock += orderGoodsNum[`${goodsListItem.goods_id}_${goodsListItem.goods_sku}_${goodsListItem.store_house_id}`]
      } else if (operation === "reduce") {
        // 库存减
        goodsItemStock.stock -= orderGoodsNum[`${goodsListItem.goods_id}_${goodsListItem.goods_sku}_${goodsListItem.store_house_id}`]
        if (goodsItemStock.stock < 0) {
          // eslint-disable-next-line prettier/prettier
          msg += `${goodsListItem.goods_name} ${goodsListItem.goods_sku} 库存仅剩 ${goodsListItem.stock}，不足订单 ${orderGoodsNum[`${goodsListItem.goods_id}_${goodsListItem.goods_sku}_${goodsListItem.store_house_id}`]} 过帐 \n`
        }
      } else if (operation === "cover") {
        // 库存覆盖
        goodsItemStock.stock = orderGoodsNum[`${goodsListItem.goods_id}_${goodsListItem.goods_sku}_${goodsListItem.store_house_id}`]
      }
      goodsAttrList.push(goodsItemStock)
    } else {  // 商品库存信息不存在则需要向 GoodsAttrValue 中插入新数据
      const item = { ...goodsListItem, sku: goodsListItem?.goods_sku }
      delete item.id  // 此处 item.id 是 orderGoods 的id 并非 GoodsAttrValue 的id, 需delete
      if (operation === "add") {  // 库存加
        goodsItemStock.stock = orderGoodsNum[`${item.goods_id}_${item.sku}`]
      } else if (operation === "reduce") {  // 库存减
        goodsItemStock.stock =
          0 - orderGoodsNum[`${item.goods_id}_${item.sku}`]
        if (goodsItemStock.stock < 0) {  // 记录库存是否小于 0
          // eslint-disable-next-line prettier/prettier
          msg += `${item.goods_name} ${item.goods_sku} 库存仅剩 ${item.stock}，不足订单 ${orderGoodsNum[`${item.goods_id}_${item.goods_sku}`]} 过帐 \n`
        }
      } else if (operation === "cover") { // 库存覆盖
        goodsItemStock.stock = orderGoodsNum[`${item.goods_id}_${item.sku}`]
      }
      const itemValue = GoodsAttrValue.defaultValue(item);
      console.log("类==itemValue： %s==", JSON.stringify(itemValue));
      goodsAttrList.push(itemValue)
    }
    if (index === goods_list.length - 1) {
      // const goodsAttrValue = _.cloneDeep(goodsAttrList)
      console.log("1--goodsAttrList==%s==", JSON.stringify(goodsAttrList));
      const goodsAttrValue = JSON.parse(JSON.stringify(goodsAttrList))
      console.log("2--goodsAttrValue==%s==", JSON.stringify(goodsAttrValue));
      const attrValueRes = await GoodsAttrValue.bulkCreate(goodsAttrValue, {
        updateOnDuplicate:
          [
            'goods_id', 'goods_name', 'sku', 'store_house_id', 'stock', 'sales', 'price', 'cost_price', 'image', 'weight', 'volume', 'sort', 'update_time'
          ]
      })
      console.log("商品库存更新结果： %s==", JSON.stringify(attrValueRes));
      return { data: attrValueRes };
    }
  }
  // if (goodsStocks.length) {
  //   for (let i = 0; i < goodsStocks.length; i++) {
  //     const item = goodsStocks[i]
  //     console.log(
  //       "updataStock--goodsStocks[i].stock: %s - %s==",
  //       goodsStocks[i].stock,
  //       orderGoodsNum[`${item.goods_id}_${item.sku}`]
  //     )

  //     if (operation === "add") {
  //       // 库存加
  //       goodsStocks[i].stock += orderGoodsNum[`${item.goods_id}_${item.sku}`]
  //     } else if (operation === "reduce") {
  //       // 库存减
  //       goodsStocks[i].stock -= orderGoodsNum[`${item.goods_id}_${item.sku}`]
  //       if (goodsStocks[i].stock < 0) {
  //         // eslint-disable-next-line prettier/prettier
  //         msg += `${item.goods_name} ${item.goods_sku} 库存仅剩 ${item.stock}，不足订单 ${orderGoodsNum[`${item.goods_id}_${item.goods_sku}`]} 过帐 \n`
  //       }
  //     } else if (operation === "cover") {
  //       // 库存覆盖
  //       goodsStocks[i].stock = orderGoodsNum[`${item.goods_id}_${item.sku}`]
  //     }
  //     if (i === goodsStocks.length - 1) {
  //       if (isAllowLoad && msg) {
  //         return { data: null, msg, code: 500 }
  //       } else {
  //         console.log(
  //           "updataStock--2-i=: %s-goodsStocks: %s==",
  //           i,
  //           JSON.stringify(goodsStocks)
  //         )
  //         const attrList = JSON.parse(JSON.stringify(goodsStocks))
  //         const attrResult = await GoodsAttrValue.bulkCreate(attrList, {
  //           updateOnDuplicate: [
  //             "goods_id",
  //             "goods_name",
  //             "sku",
  //             "store_house_id",
  //             "stock",
  //             "sales",
  //             "price",
  //             "cost_price",
  //             "image",
  //             "weight",
  //             "volume",
  //             "sort",
  //             "update_time"
  //           ]
  //         })
  //         console.log(
  //           "更新库存--GoodsController.updataStock--attrResult:%s==",
  //           JSON.stringify(attrResult)
  //         )
  //         return { data: attrResult }
  //         // GoodsAttrValue.bulkCreate(attrList
  //         //   , {
  //         //     updateOnDuplicate:
  //         //       [
  //         //         'goods_id', 'goods_name', 'sku', 'store_house_id', 'stock', 'sales', 'price', 'cost_price', 'image', 'weight', 'volume', 'sort', 'update_time'
  //         //       ]
  //         //   }
  //         // ).then(attrResult => {
  //         //   console.log("更新库存:成功--GoodsController.updataStock--attrResult:%s==", JSON.stringify(attrResult));
  //         //   return { data: attrResult };
  //         // }).catch(err => {
  //         //   console.log("更新库存:出错--GoodsController.updataStock--attrResult:%s==", JSON.stringify(err));
  //         //   return "";
  //         // })
  //       }
  //     }
  //   }
  // }
  // return ""
}

// 判断订单类型 出库还是入库
// order_type 订单类型：1: 采购入库，2: 销售出库，3: 同价调拨， 4: 其他入库，5: 采购退货，6: 报溢单，7: 报损单，8: 其他出库

const handleOrderType = type => {
  if (['1', '4'].includes(type)) {
    return 1;
  }
  else if (['2', '5', '6', '7', '8'].includes(type)) {
    return -1;
  }
  else {
    return 0;
  }
}

module.exports = {
  createGoods,
  createGoods2: async params => {
    const {
      goods_name,
      full_goods_name,
      cat_id,
      attr = "",
      stock = "0",
      sales = "0",
      unit_name,
      unit_name2 = "",
      unit_convert = 1,
      unit_convert2 = 1,
      weight = 0,
      desc = "",
      sort = 500,
      store_id,
      is_hot = 0,
      is_recommend = 0,
      status = 1,
      is_delete = 0,
      slider_image = "",
      content
    } = params
    let isFlag = false
    let goods = null
    try {
      goods = await Goods.findOrCreate({
        where: { store_id, goods_name, full_goods_name },
        defaults: {
          goods_name,
          full_goods_name,
          cat_id,
          attr,
          stock,
          sales,
          unit_name,
          unit_name2,
          unit_convert,
          unit_convert2,
          weight,
          desc,
          sort,
          store_id,
          is_hot,
          is_recommend,
          status,
          is_delete,
          slider_image,
          content
        }
      })
      isFlag = utils.handleCreateIsSuccess(goods)
      console.log(
        "createGoods--goods:%s--isFlag: %s==",
        JSON.stringify(goods),
        isFlag
      )
      if (isFlag) {
        const attr = {
          goods_id: goods[0].id,
          attr_name: "规格",
          attr_values: "默认"
        }
        const goodsAttr = await GoodsAttr.findOrCreate({
          where: { goods_id: attr.goods_id, attr_name: attr.attr_name },
          defaults: { ...attr }
        })
        console.log("goodsAttr==%s==", JSON.stringify(goodsAttr))
        const resultData = {
          attrs: [attr.attr_name],
          values: [attr.attr_values]
        }
        const attrResult = {
          goods_id: goods[0].id,
          result: JSON.stringify(resultData)
        }
        const goodsAttrResult = await GoodsAttrResult.findOrCreate({
          where: { goods_id: attrResult.goods_id },
          defaults: { ...attrResult }
        })
        console.log("goodsAttrResult==%s==", JSON.stringify(goodsAttrResult))
      }
    } catch (e) {
      // console.log('createGoods--e==%s', e);
      return null
    }
    // console.log('goods==%s==', JSON.stringify(goods || '{e:""}'));
    return goods
  },
  // 获取门店所有商品
  getStoreGoods: async function (store_id) {
    const goods = await this.goodsIndex(store_id)
    // const sql = "select * from "
    // sqlConn(sql, [], (res) => {
    //   console.log('');
    //   console.log('sqlConn--res:%s==', JSON.stringify(res));
    // })
    return goods
  },
  goodsIndex: async function (store_id) {
    const list = await Goods.findAll({
      where: { store_id },
      include: [
        // {
        //   association: GoodsHasOneAttrConfig,
        //   attributes: [
        //     // Sequelize.col('config'), 'config'
        //     [Sequelize.col("config"), "config"]
        //   ],
        //   // where: {},
        //   // required: false
        // },
        {
          association: GoodsHasManyAttrValue,
          as: "attrValue",
          order: [
            ["sort", "ASC"]
          ],
          include: [
            {
              association: GoodsHasManyStock,
              all: true
            }
          ]
          // order: [["attrValue.sort", "ASC"]]
        },
        
      ],
      order: [
        ["sort", "ASC"],
        ["attrValue", "sort", "ASC"]
        // [GoodsHasManyAttrValue, "sort", "ASC"]
      ]
    })

    console.log('goodsIndex--list--%s==', JSON.stringify(list))
    const list2 = list.map(d => {
      console.log('d.attrValue--%s==', JSON.stringify(d.attrValue));
      const dd = JSON.parse(JSON.stringify(d));

      if (d?.attrValue) {
        const attrValue = d.attrValue.map(a => {
          const aa = JSON.parse(JSON.stringify(a));
          // const attrItem = Object.assign({}, dd, aa);
          const attrItem = { ...dd, ...aa };
          delete attrItem.attrValue;
          return attrItem;
        });
        console.log('goodsIndex--attrValue-2-%s==', JSON.stringify(attrValue))
        dd.attrValue = JSON.parse(JSON.stringify(attrValue));
      }
      return dd;
    })
    console.log('goodsIndex--list-2-%s==', JSON.stringify(list2))

    const count = list.length || 0
    return { count, list: list2 }
  },
  goodsIndex2: async function (store_id) {
    const list = await Goods.findAll({
      where: { store_id },
      include: [
        // {
        //   association: GoodsHasOneAttrConfig,
        //   attributes: [
        //     // Sequelize.col('config'), 'config'
        //     [Sequelize.col("config"), "config"]
        //   ]
        //   // where: {},
        //   // required: false
        // },
        {
          association: GoodsHasManyAttrValue,
          order: [["attrValue.sort", "ASC"]]
        }
      ],
      order: [
        ["sort", "ASC"],
        [GoodsHasManyAttrValue, "sort", "ASC"]
      ]
    })
    // console.log('goodsIndex--%s==', JSON.stringify(list));
    const count = list.length || 0
    // const { count, rows } = await Goods.findAndCountAll({
    //   order: [['sort', 'ASC']],
    //   where: { store_id },
    //   include:  [
    //     {
    //       association: GoodsHasOneAttr,
    //       // attributes:[
    //       //   [Sequelize.col('config'), 'config'],
    //       // ],
    //       where: {},
    //       required: true
    //     }
    //   ]
    // });
    // rows.forEach(d => {
    //   let item = JSON.parse(JSON.stringify(d));
    //   // item.attrData = JSON.parse(d.attrData?.config || '{}');
    //   list.push(item);
    // })
    return { count, list }
  },
  // 获取分店商品详情
  getStoreGoodsDetail: async function (id) {
    const result = await Goods.findByPk(id, {
      order: [["sort", "ASC"]],
      where: { goods_id: id },
      include: [
        {
          association: GoodsHasOneAttrConfig,
          attributes: [[Sequelize.col("config"), "config"]]
        },
        {
          association: GoodsHasManyAttrValue,
          order: [["sort", "ASC"]]
        }
      ]
    })
    if (!result) {
      return null
    }
    const data = JSON.parse(JSON.stringify(result))
    // console.log('data==%s==', JSON.stringify(data));
    // data.attrConfig = JSON.parse(data.attrConfig?.config || '{}')

    return data
  },
  updateGoods,
  bulkCreateGoodsAttr,
  getGoodsAttr: async function (id, goods_id) {
    const goodsAttr = await GoodsAttr.findOne({ where: { id, goods_id } })
    return goodsAttr
  },
  addGoodsAttr: async function (
    id,
    goods_id,
    attr_name,
    attr_values,
    is_delete
  ) {
    const goods = await Goods.findOne({ where: { goods_id } })
    if (goods) {
    }
    return goodsAttr
  },
  getGoodsAttrConfig: async function (id, goods_id, store_id) { },
  updataStock
}
